package com.httputils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.myfp.myfund.AppBean;


/**
 * 功能：网络连接器
 * 
 * @author User
 * 
 */
public class ConnMachine {

	private HttpClient client;
	private boolean reconnect = false;// 是否重连
	private HttpPost postRequest;
	public boolean isCancel;
	private HttpResponse response;
	private int j,x=0;
	private HttpGet getRequest;
	private boolean showProgress;
	private Handler handler;
	private HttpPut putRequest;
	private String result;

	public ConnMachine(HttpClient client, boolean reconnect) {
		super();
		this.client = client;
		this.reconnect = reconnect;
	}

	public ConnMachine(HttpClient client) {
		super();
		this.client = client;
	}

	/**
	 * 普通Http的post请求
	 * 
	 * @param list
	 * @param url
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public String requestPost(List<NameValuePair> list, String url)
			throws Exception {
		String resStr = null;
		InputStream in = null;
		ByteArrayOutputStream out = null;
		// 应用公用参数
		list.add(new BasicNameValuePair("imei", TransactionValues.DEVICEIMEI));
		list.add(new BasicNameValuePair("lon", TransactionValues.longitude));
		list.add(new BasicNameValuePair("lat", TransactionValues.latitude));
		try {
			postRequest = new HttpPost(url);

			if (true == reconnect) {
				// request.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new
				// DefaultHttpMethodRetryHandler());
			}
			HttpEntity entity = new UrlEncodedFormEntity(list,
					NetworkConstant.ENCODE);
			postRequest.setEntity(entity);
			if (isCancel) {
				throw new CloseRequestException();
			}
			response = client.execute(postRequest);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity rentity = response.getEntity();
				if (entity != null) {
					in = rentity.getContent();
					out = new ByteArrayOutputStream();
					byte[] arr = new byte[1024 * 8];
					int len = 0;
					while ((len = in.read(arr)) > 0) {
						if (isCancel) {
							throw new CloseRequestException();
						}
						out.write(arr, 0, len);
						out.flush();
					}
					resStr = out.toString(NetworkConstant.ENCODE);
					Log.d("ConnMachine", resStr);
				}
			}
			return resStr;
		} finally {
			closeStream(in, out);
		}
	}

	@SuppressWarnings("resource")
	public String requestImage(String url, List<NameValuePair> params,
			String path) throws Exception {
		String resStr = null;
		InputStream in = null;
		ByteArrayOutputStream out = null;
		// 应用公用参数
		// params.addPart("phoneType", new StringBody(
		// TransactionValues.phoneType));
		// params.addPart("userToken", new StringBody(
		// TransactionValues.userToken));
		// params.addPart("userId", new StringBody(
		// CacheBean.cacheBean.getUerId()));
		// params.addPart("pointX", new
		// StringBody(TransactionValues.longitude));
		// params.addPart("pointY", new StringBody(TransactionValues.latitude));
		// params.addPart("cityCode", new
		// StringBody(TransactionValues.cityCode));
		File file = new File(path);
		InputStream in1 = new FileInputStream(file);
		OutputStream out1 = new ByteArrayOutputStream();
		byte[] arr1 = new byte[1024 * 8];
		int len1 = 0;
		while ((len1 = in1.read(arr1)) > 0) {
			if (isCancel) {
				throw new CloseRequestException();
			}
			out1.write(arr1, 0, len1);
			out1.flush();
		}
		String img=out1.toString();
		 img=URLEncoder.encode(img, "UTF-8");
		out1.close();
		in1.close();
		// FileBody body = new FileBody(file);
		params.add(new BasicNameValuePair("phoneType",
				TransactionValues.phoneType));
		params.add(new BasicNameValuePair("userToken",
				TransactionValues.userToken));
		params.add(new BasicNameValuePair("pointX", TransactionValues.longitude));
		params.add(new BasicNameValuePair("pointY", TransactionValues.latitude));
		params.add(new BasicNameValuePair("cityCode",
				TransactionValues.cityCode));
		params.add(new BasicNameValuePair("attach1", img));
		try {
			postRequest = new HttpPost(url);
			// if (1 == NetworkConstant.COMM_TYPE)
			postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			// postRequest.setEntity(params);
			if (isCancel) {
				throw new CloseRequestException();
			}
			response = client.execute(postRequest);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				Log.d("ConnMachine", "联网状态码："
						+ response.getStatusLine().getStatusCode());
				HttpEntity rentity = response.getEntity();
				if (params != null) {
					in = rentity.getContent();
					out = new ByteArrayOutputStream();
					byte[] arr = new byte[1024 * 8];
					int len = 0;
					while ((len = in.read(arr)) > 0) {
						if (isCancel) {
							throw new CloseRequestException();
						}
						out.write(arr, 0, len);
						out.flush();
					}
					resStr = out.toString(NetworkConstant.ENCODE);
				}
			}
			return resStr;
		} finally {
			closeStream(in, out);
		}
	}

	/**
	 * 大文件下载默认不显示进度条 调用setHandler方法可以回传进度值到handler
	 * 
	 * @param url
	 *            连接地址
	 * @param direct
	 *            目录名
	 * @return -2表示空间不足-1表示失败 0 表示成功1表示文件已经存在
	 * @throws
	 * 
	 */
	@SuppressWarnings("resource")
	public int getRemoteFileInputStream(String url, String direct,
			String fileName) throws Exception {
		InputStream in = null;
		OutputStream out = null;
		j = 0;
		direct = "/storage/extSdCard" + NetworkConstant.APK_DIR;
		File dirfile = new File(direct);
		if (!dirfile.exists()) {
			dirfile.mkdirs();
		}
		File file = new File(direct, fileName);
		if (file.exists()) {// 如果该文件曾经下载过则不再下载此处只根据路径名字来判断文件是否为同一次注意使用
			return NetworkConstant.FILE_EXIT;// 文件已存在返回码
		}
		try {
			getRequest = new HttpGet(url);
			if (true == reconnect) {
				// get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new
				// DefaultHttpMethodRetryHandler());
			}
			if (isCancel) {
				throw new CloseRequestException();
			}
			response = client.execute(getRequest);
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				HttpEntity entity = response.getEntity();
				long curBytes = 0, totalBytes = 0;
				totalBytes = entity.getContentLength();
				if (entity != null) {
					long lenth = entity.getContentLength();
					if (lenth > MyUtils.getSdRemainRoom()) {
						return NetworkConstant.SD_NOSPACE;// sd卡空间不足 返回码
					} else {
						in = entity.getContent();

						out = new FileOutputStream(file);
						byte[] arr = new byte[1024 * 8];
						int len = 0;
						while ((len = in.read(arr)) > 0) {
							if (isCancel) {
								throw new CloseRequestException();
							}
							out.write(arr, 0, len);
							out.flush();
							if (showProgress) {
								curBytes += len;
								j = ((int) (curBytes / (float) totalBytes * 100));
								Message msg = new Message();
								msg.what = j;
								handler.sendMessage(msg);
							}

						}
					}
				}
			}
			return NetworkConstant.RIGHT_CODE;// 获取成功返回码
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 根据给定的URL获取文件读取流
	 */
	public InputStream getRemoteFileInputStream(String url) {
		HttpResponse response;
		InputStream is = null;

		if (client == null) {
			return null;
		}

		getRequest = new HttpGet(url);
		try {
			response = client.execute(getRequest);
		} catch (Exception e1) {
			e1.printStackTrace();
			return null;
		}

		if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				try {
					is = entity.getContent();
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
			}
		} else {
			return null;
		}

		return is;
	}

	/**
	 * 获取小文件
	 * 
	 * @param url
	 * @param appBean
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public byte[] getBytes(String url, final AppBean appBean) throws Exception {
		byte[] is = null;
		InputStream in = null;

		ByteArrayOutputStream out = null;

		try {
			if (null == client) {
				return null;
			}
			postRequest = new HttpPost(url);
			if (true == reconnect) {
				// get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new
				// DefaultHttpMethodRetryHandler());
			}
			if (isCancel) {
				throw new CloseRequestException();
			}
			response = client.execute(postRequest);
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					in = entity.getContent();
					out = new ByteArrayOutputStream();
					byte[] arr = new byte[1024 * 8];
					int len = 0;
					while ((len = in.read(arr)) > 0) {
						if (isCancel) {
							throw new CloseRequestException();
						}
						out.write(arr, 0, len);
						out.flush();
					}
					is = out.toByteArray();
				}
			}
			return is;
		} finally {
			closeStream(in, out);
		}
	}

	/**
	 * 
	 * @param handler
	 *            传递显示进度的handler
	 */
	public void setHandler(Handler handler) {
		showProgress = true;// 置显示进度true
		this.handler = handler;

	}

	/**
	 * 
	 * 采用json方式的post请求
	 * 
	 * @param url
	 *            请求的url
	 * @param json
	 *            请求参数
	 * @param headerMap
	 *            请求头信息
	 * @return 返回的json数据
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public String requestPostByMap(String url, Map<String, Object> requestMap,
			Map<String, String> headerMap) throws Exception {
		String resStr = null;
		InputStream in = null;
		ByteArrayOutputStream out = null;
		if (headerMap == null) {
			headerMap = new HashMap<String, String>();
		}

		try {
			postRequest = new HttpPost(url);
			if (true == reconnect) {
				// get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new
				// DefaultHttpMethodRetryHandler());
			}
			// 添加头信息
			Set<String> keys = headerMap.keySet();
			if (keys != null) {
				Iterator<String> iterator = keys.iterator();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					String value = headerMap.get(key);
					postRequest.addHeader(key, value);
				}
			}
			// Log.d("ConnMachine","本地JSON数据"+json);
			// Log.d("ConnMachine","本地JSON数据走了这一步1");
			// StringEntity se = new StringEntity(json, NetworkConstant.ENCODE);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			Set<String> mapKeys = requestMap.keySet();
			if (keys != null) {
				Iterator<String> iterator = mapKeys.iterator();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					String value = (String) requestMap.get(key);
					postRequest.addHeader(key, value);
					params.add(new BasicNameValuePair(key, value));
				}
				postRequest.setEntity(new UrlEncodedFormEntity(params,
						HTTP.UTF_8));
			}
			if (isCancel) {
				Log.d("ConnMachine", "本地JSON数据走了这一步2");
				throw new CloseRequestException();
			}
			response = client.execute(postRequest);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				Log.d("ConnMachine", "网络请求状态码---->>>"
						+ response.getStatusLine().getStatusCode());
				result = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
				Log.d("ConnMachine", "返回的数据---->>>" + result);
				// HttpEntity entity = response.getEntity();
				// if (entity != null) {
				// in = entity.getContent();
				// out = new ByteArrayOutputStream();
				// byte[] arr = new byte[1024 * 8];
				// int len = 0;
				// while ((len = in.read(arr)) != -1) {
				// if (isCancel) {
				// throw new CloseRequestException();
				// }
				// out.write(arr, 0, len);
				// out.flush();
				// }
				// resStr = out.toString(NetworkConstant.ENCODE);
				// Log.d("MSG", "返回数据:" + result);
				// }
			}
			return result;
		} finally {
			closeStream(in, out);
		}
	}

	/**
	 * 
	 * 采用json方式的put请求
	 * 
	 * @param url
	 *            请求的url
	 * @param json
	 *            请求参数
	 * @param headerMap
	 *            请求头信息
	 * @return 返回的json数据
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public String requestPutByJson(String url, String json,
			Map<String, String> headerMap) throws Exception {
		String resStr = null;
		InputStream in = null;
		ByteArrayOutputStream out = null;

		try {
			putRequest = new HttpPut(url);
			if (true == reconnect) {
				// get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new
				// DefaultHttpMethodRetryHandler());
			}
			// 添加头信息
			Set<String> keys = headerMap.keySet();
			if (keys != null) {
				Iterator<String> iterator = keys.iterator();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					String value = headerMap.get(key);
					putRequest.addHeader(key, value);
				}
			}

			if (!TextUtils.isEmpty(json)) {
				StringEntity se = new StringEntity(json, NetworkConstant.ENCODE);
				putRequest.setEntity(se);
			}
			if (isCancel) {
				throw new CloseRequestException();
			}
			response = client.execute(putRequest);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					in = entity.getContent();
					out = new ByteArrayOutputStream();
					byte[] arr = new byte[1024 * 8];
					int len = 0;
					while ((len = in.read(arr)) != -1) {
						if (isCancel) {
							throw new CloseRequestException();
						}
						out.write(arr, 0, len);
						out.flush();
					}
					resStr = out.toString(NetworkConstant.ENCODE);
				}
			}
			return resStr;
		} finally {
			closeStream(in, out);
		}
	}

	/**
	 * 采用json方式的get请求
	 * 
	 * @param //url1
	 *            要请求的url
	 * @param //sb
	 *            封装了请求参数
	 * @param headerMap
	 *            请求头信息
	 * @return 返回的json数据，考虑到程序的拓展性，json数据结构的多样化，此处不做json解析，放到具体页面
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public String requestGetByJson(String url, String jason,
			Map<String, String> headerMap) throws Exception {
		String resStr = null;
		InputStream in = null;
		ByteArrayOutputStream out = null;
		try {
			url = url + jason;
			getRequest = new HttpGet(url);
			if (true == reconnect) {
				// get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new
				// DefaultHttpMethodRetryHandler());
			}
			// 添加头信息
			Set<String> keys = headerMap.keySet();
			if (keys != null) {
				Iterator<String> iterator = keys.iterator();
				while (iterator.hasNext()) {
					String key = (String) iterator.next();
					String value = headerMap.get(key);
					putRequest.addHeader(key, value);
				}
			}
			if (isCancel) {
				throw new CloseRequestException();
			}
			response = client.execute(getRequest);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					in = entity.getContent();
					out = new ByteArrayOutputStream();
					byte[] arr = new byte[1024 * 8];
					int len = 0;
					while ((len = in.read(arr)) != -1) {
						if (isCancel) {
							throw new CloseRequestException();
						}
						out.write(arr, 0, len);
						out.flush();
					}
					resStr = out.toString(NetworkConstant.ENCODE);
				}
			}
			return resStr;
		} finally {
			closeStream(in, out);
		}

	}

	/**
	 * 关闭流
	 * 
	 * @param in
	 * @param out
	 */
	private void closeStream(InputStream in, ByteArrayOutputStream out) {
		try {
			if (in != null) {
				in.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (out != null) {
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭联网任务
	 */
	public boolean close() {
		try {
			if (postRequest != null) {
				postRequest.abort();
			}
			if (putRequest != null) {
				putRequest.abort();
			}
			if (getRequest != null) {
				getRequest.abort();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		isCancel = true;
		return true;
	}

	public Bitmap getImage(String ImageURL) {
		return DownloadImage(ImageURL);
	}

	private Bitmap DownloadImage(String URL) {
		Bitmap bitmap = null;
		InputStream in = null;
		try {
			in = OpenHttpConnection(URL);
			if (null == in) {
				return null;
			}
			bitmap = BitmapFactory.decodeStream(in);
			in.close();
		} catch (Exception e1) {
			e1.printStackTrace();
			return null;
		}

		return bitmap;
	}

	private InputStream OpenHttpConnection(String urlString) {
		InputStream in = null;
		int response = -1;
		URL url;
		try {
			url = new URL(urlString);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		URLConnection conn = null;
		try {
			conn = url.openConnection();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		if (!(conn instanceof HttpURLConnection)) {
			return null;
		}
		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setConnectTimeout(NetworkConstant.COMM_TIMEOUT);
			httpConn.setReadTimeout(NetworkConstant.COMM_TIMEOUT);
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}
		} catch (Exception ex) {
			return null;
		}

		return in;
	}
}
